# Create your views here.
import datetime

import arrow
from django.db.models import Sum
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from usercount import constants
from usercount.constants import address_change
from usercount.utils import GenerateUserData
from users.models import User
from .models import UserCount
from rest_framework.generics import GenericAPIView
from .serializers import UserCountSerializer
from django_redis import get_redis_connection
from users.utils import OpenidUtils


class UserStatisticsView(GenericAPIView):
    serializer_class = UserCountSerializer

    def post(self, request):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        query_params = request.data
        oauth = OpenidUtils(query_params.get('jscode'))
        user = oauth.get_openid()

        html_or_goods = query_params.get('html_or_goods')
        stay_time = query_params.get('stay_time')
        end_flag = query_params.get('end_flag')
        redis_conn = get_redis_connection('usercount')
        pl = redis_conn.pipeline()

        if redis_conn.exists('user_%s' % user):
            redis_count = redis_conn.hgetall('user_%s' % user)
            count_hash = {}
            for key, value in redis_count.items():
                count_hash[key.decode('utf-8')] = value.decode('utf-8')
            # 累计浏览量
            html_count = int(count_hash['html_count']) + 1
            if html_or_goods == 'goods':
                goods_count = int(count_hash['goods_count']) + 1
            else:
                goods_count = int(count_hash['goods_count'])

            # 累计时间
            all_stay_time = int(count_hash['all_stay_time']) + int(stay_time)
            pl.hset('user_%s' % user, 'html_count', html_count)
            pl.hset('user_%s' % user, 'goods_count', goods_count)
            pl.hset('user_%s' % user, 'all_stay_time', all_stay_time)
        else:
            # 初始化
            pl.hset('user_%s' % user, 'html_count', 1)
            pl.hset('user_%s' % user, 'goods_count', 0)
            pl.hset('user_%s' % user, 'all_stay_time', stay_time)

            # 设置过期时间
            pl.expire('user_%s' % user, constants.USER_COUNT_REDIS_EXPIRES)
        pl.execute()
        # # 判断是否结束
        if end_flag:
            html_count = redis_conn.hget('user_%s' % user, 'html_count')
            goods_count = redis_conn.hget('user_%s' % user, 'goods_count')
            all_stay_time = redis_conn.hget('user_%s' % user, 'all_stay_time')
            usercount = UserCount.objects.create(
                username=user,
                web_visit_count=html_count,
                goods_visit_count=goods_count,
                stay_time=all_stay_time
            )
            usercount.save()
            # 清除掉redis缓存中的数据
            redis_conn.delete('user_%s' % user)
        return Response({'message': 'ok', 'ResultCode': 1}, status=status.HTTP_201_CREATED)


# 展示今日/昨日/本月/今年访客统计
class AllUserStatisticView(APIView):
    # permission_classes = [IsAuthenticated]

    def get(self, request):
        # 获取当前时间
        today = datetime.datetime.now().date()
        # 昨日
        yesterday = datetime.datetime.now().date() - datetime.timedelta(days=1)
        # 前天
        before_yesterday = datetime.datetime.now().date() - datetime.timedelta(days=2)
        # 本月
        current_month = datetime.datetime.now().month
        # 上个月
        last_month = int(arrow.now().shift(months=-1).format("MM"))
        # 本年
        current_year = datetime.datetime.now().year
        # 去年
        last_year = int(arrow.now().shift(years=-1).format("YYYY"))

        result_list = {}
        # 实例化工具类
        Get_data = GenerateUserData()
        # 获取今日访问的相关信息
        today_list = {}
        today_old_count = 0
        today_new_count = 0
        # 获取老用户
        all_before_today_list = Get_data.get_old_user_list(yesterday)

        # 当天访客总数
        today_count = UserCount.objects.filter(create_time__gte=today).values('username').distinct().count()
        if today_count:
            # 新访问用户  第一次访问的新用户
            today_new_user = UserCount.objects.filter(create_time__gte=today).values('username').distinct()
            for i in today_new_user:
                if i['username'] in all_before_today_list:
                    # 老访问数
                    today_old_count += 1
                else:
                    # 新访问数
                    today_new_count += 1

            # 当天的总浏览量
            # 初始值为0
            today_web_visit_count_result = 0
            today_web_visit_count = UserCount.objects.filter(create_time__gte=today).values(
                'web_visit_count').aggregate(
                web_all_count=Sum('web_visit_count'))
            if today_web_visit_count['web_all_count']:
                today_web_visit_count_result = today_web_visit_count['web_all_count']

            # 当天的商品总浏览量
            # 初始值为0
            today_goods_visit_count_result = 0
            today_goods_visit_count = UserCount.objects.filter(create_time__gte=today).values(
                'goods_visit_count').aggregate(
                goods_all_count=Sum('goods_visit_count'))
            if today_goods_visit_count['goods_all_count']:
                today_goods_visit_count_result = today_goods_visit_count['goods_all_count']

            # 总的浏览时长
            stay_time = UserCount.objects.filter(create_time__gte=today).values('stay_time').aggregate(
                stay_all_time=Sum('stay_time'))
            stay_time_result = stay_time['stay_all_time']
            today_avg_time_result = Get_data.get_avg_time(stay_time_result, today_goods_visit_count_result)
        else:
            # 当天无任何访客
            today_count = 0
            today_new_count = 0
            today_old_count = 0
            today_web_visit_count_result = 0
            today_goods_visit_count_result = 0
            today_avg_time_result = ("%02d:%02d:%02d" % (0, 0, 0))

        ###
        # 获取昨日访问的相关信息
        yesterday_list = {}
        yesterday_old_count = 0
        yesterday_new_count = 0
        # 获取截至到昨日所有用户的用户名
        all_before_yesterday_list = Get_data.get_old_user_list(before_yesterday)

        # 昨天访客总数
        yesterday_count = UserCount.objects.filter(create_time__gte=yesterday, create_time__lt=today).values(
            'username').distinct().count()
        if yesterday_count:
            # 新访问用户
            yesterday_new_user = UserCount.objects.filter(create_time__gte=yesterday, create_time__lt=today).values(
                'username').distinct()
            for i in yesterday_new_user:
                if i['username'] in all_before_yesterday_list:
                    # 老访问数
                    yesterday_old_count += 1
                else:
                    # 新访问数
                    yesterday_new_count += 1

            # 昨日的总浏览量
            yesterday_web_visit_count_result = 0  # 初始值为0
            yesterday_web_visit_count = UserCount.objects.filter(create_time__gte=yesterday,
                                                                 create_time__lt=today).values(
                'web_visit_count').aggregate(
                web_all_count=Sum('web_visit_count'))
            if yesterday_web_visit_count['web_all_count']:
                yesterday_web_visit_count_result = yesterday_web_visit_count['web_all_count']

            # 昨日的商品总浏览量
            yesterday_goods_visit_count_result = 0  # 初始值为0
            yesterday_goods_visit_count = UserCount.objects.filter(create_time__gte=yesterday,
                                                                   create_time__lt=today).values(
                'goods_visit_count').aggregate(
                goods_all_count=Sum('goods_visit_count'))
            if yesterday_goods_visit_count['goods_all_count']:
                yesterday_goods_visit_count_result = yesterday_goods_visit_count['goods_all_count']
            # 总的浏览时长
            stay_time = UserCount.objects.filter(create_time__gte=yesterday, create_time__lt=today).values(
                'stay_time').aggregate(
                stay_all_time=Sum('stay_time'))
            stay_time_result = stay_time['stay_all_time']
            yesterday_avg_time_result = Get_data.get_avg_time(stay_time_result, yesterday_goods_visit_count_result)
        else:
            yesterday_count = 0
            yesterday_new_count = 0
            yesterday_old_count = 0
            yesterday_web_visit_count_result = 0
            yesterday_goods_visit_count_result = 0
            yesterday_avg_time_result = ("%02d:%02d:%02d" % (0, 0, 0))

        # 获取本月访问的相关信息
        month_list = {}
        month_old_count = 0
        month_new_count = 0
        # 获取截至到昨日所有用户的用户名
        all_before_month_list = []
        # 如果当前月份是一月份，上个月是12月的话，year 需要变成去年
        if last_month == 12:
            all_before_month_username = UserCount.objects.filter(create_time__month=last_month,
                                                                 create_time__year=last_year).values(
                'username').distinct()
        else:
            all_before_month_username = UserCount.objects.filter(create_time__month=last_month,
                                                                 create_time__year=current_year).values(
                'username').distinct()
        if all_before_month_username:
            for i in all_before_month_username:
                all_before_month_list.append(i['username'])

        # 当月访客总数
        month_count = UserCount.objects.filter(create_time__month=current_month, create_time__year=current_year).values(
            'username').distinct().count()
        # 新访问数
        if month_count:
            # 新访问用户
            month_new_user = UserCount.objects.filter(create_time__month=current_month,
                                                      create_time__year=current_year).values(
                'username').distinct()
            for i in month_new_user:
                if i['username'] in all_before_month_list:
                    # 老访问数
                    month_old_count += 1
                else:
                    # 新访问数
                    month_new_count += 1

            # 本月的总浏览量
            month_web_visit_count_result = 0  # 初始值为0
            month_web_visit_count = UserCount.objects.filter(create_time__month=current_month,
                                                             create_time__year=current_year).values(
                'web_visit_count').aggregate(
                web_all_count=Sum('web_visit_count'))
            if month_web_visit_count['web_all_count']:
                month_web_visit_count_result = month_web_visit_count['web_all_count']

            # 昨日的商品总浏览量
            month_goods_visit_count_result = 0
            month_goods_visit_count = UserCount.objects.filter(create_time__month=current_month,
                                                               create_time__year=current_year).values(
                'goods_visit_count').aggregate(
                goods_all_count=Sum('goods_visit_count'))
            if month_goods_visit_count['goods_all_count']:
                month_goods_visit_count_result = month_goods_visit_count['goods_all_count']

            # 总的浏览时长
            stay_time = UserCount.objects.filter(create_time__month=current_month,
                                                 create_time__year=current_year).values(
                'stay_time').aggregate(
                stay_all_time=Sum('stay_time'))
            stay_time_result = stay_time['stay_all_time']
            month_avg_time_result = Get_data.get_avg_time(stay_time_result, month_goods_visit_count_result)
        else:
            month_count = 0
            month_new_count = 0
            month_old_count = 0
            month_web_visit_count_result = 0
            month_goods_visit_count_result = 0
            month_avg_time_result = ("%02d:%02d:%02d" % (0, 0, 0))

        # 获取今年访问的相关信息
        year_list = {}
        year_old_count = 0
        year_new_count = 0
        # 获取截至到昨日所有用户的用户名
        all_before_year_list = []
        all_before_year_username = UserCount.objects.filter(create_time__year=last_year).values('username').distinct()
        if all_before_year_username:
            for i in all_before_year_username:
                all_before_year_list.append(i['username'])
        # 今年访客总数
        year_count = UserCount.objects.filter(create_time__year=current_year).values(
            'username').distinct().count()
        # 新访问用户
        if year_count:
            # 新访问用户
            year_new_user = UserCount.objects.filter(create_time__year=current_year).values('username').distinct()
            for i in year_new_user:
                if i['username'] in all_before_year_list:
                    # 老访问数
                    year_old_count += 1
                else:
                    # 新访问数
                    year_new_count += 1
            # 今年的总浏览量
            year_web_visit_count_result = 0  # 初始化
            year_web_visit_count = UserCount.objects.filter(create_time__year=current_year).values(
                'web_visit_count').aggregate(
                web_all_count=Sum('web_visit_count'))
            if year_web_visit_count['web_all_count']:
                year_web_visit_count_result = year_web_visit_count['web_all_count']

            # 今年的商品总浏览量
            year_goods_visit_count_result = 0  # 初始化
            year_goods_visit_count = UserCount.objects.filter(create_time__year=current_year).values(
                'goods_visit_count').aggregate(
                goods_all_count=Sum('goods_visit_count'))
            if year_goods_visit_count['goods_all_count']:
                year_goods_visit_count_result = year_goods_visit_count['goods_all_count']

            # 总的浏览时长
            stay_time = UserCount.objects.filter(create_time__year=current_year).values(
                'stay_time').aggregate(
                stay_all_time=Sum('stay_time'))
            stay_time_result = stay_time['stay_all_time']
            year_avg_time_result = Get_data.get_avg_time(stay_time_result, year_goods_visit_count_result)
        else:
            year_count = 0
            year_new_count = 0
            year_old_count = 0
            year_web_visit_count_result = 0
            year_goods_visit_count_result = 0
            year_avg_time_result = ("%02d:%02d:%02d" % (0, 0, 0))

        # 整合今日数据
        today_list['today_count'] = today_count
        today_list['new_count'] = today_new_count
        today_list['old_count'] = today_old_count
        today_list['today_web_visit_count'] = today_web_visit_count_result
        today_list['today_goods_visit_count'] = today_goods_visit_count_result
        today_list['avg_time_result'] = today_avg_time_result

        # 整合昨日数据
        yesterday_list['yesterday_count'] = yesterday_count
        yesterday_list['new_count'] = yesterday_new_count
        yesterday_list['old_count'] = yesterday_old_count
        yesterday_list['yesterday_web_visit_count'] = yesterday_web_visit_count_result
        yesterday_list['yesterday_goods_visit_count'] = yesterday_goods_visit_count_result
        yesterday_list['avg_time_result'] = yesterday_avg_time_result

        # 整合本月数据
        month_list['month_count'] = month_count
        month_list['new_count'] = month_new_count
        month_list['old_count'] = month_old_count
        month_list['month_web_visit_count'] = month_web_visit_count_result
        month_list['month_goods_visit_count'] = month_goods_visit_count_result
        month_list['avg_time_result'] = month_avg_time_result

        # 整合今年数据
        year_list['year_count'] = year_count
        year_list['new_count'] = year_new_count
        year_list['old_count'] = year_old_count
        year_list['year_web_visit_count'] = year_web_visit_count_result
        year_list['year_goods_visit_count'] = year_goods_visit_count_result
        year_list['avg_time_result'] = year_avg_time_result

        #  返回的result
        result_list['today_list'] = today_list
        result_list['yesterday_list'] = yesterday_list
        result_list['month_list'] = month_list
        result_list['year_list'] = year_list

        result_code = 1
        return Response({'all_result': result_list, 'result_code': result_code})


class UserStatisticShowView(APIView):
    # permission_classes = [IsAuthenticated]

    def get(self, request, search_date):
        if search_date == 'today':
            date = datetime.datetime.now().date()
        elif search_date == 'yesterday':
            date = datetime.datetime.now().date() - datetime.timedelta(days=1)
        elif search_date == 'seven':
            date = datetime.datetime.now().date() - datetime.timedelta(days=7)
        elif search_date == 'thirtydays':
            date = datetime.datetime.now().date() - datetime.timedelta(days=30)
        else:
            return Response({'result_code': 0, 'message': '请求参数有误'}, status=status.HTTP_400_BAD_REQUEST)

        result_list = {}
        user_list = {}
        man = 0
        woman = 0
        province_dict_old_man = {}
        province_dict_new_man = {}
        province_dict_old_woman = {}
        province_dict_new_woman = {}
        old_man = 0
        old_woman = 0
        new_man = 0
        new_woman = 0
        # 实例化类
        Get_data = GenerateUserData()
        # 获取老用户列表
        old_user_list = Get_data.get_old_user_list(date)

        # 当天访客总数
        counts = UserCount.objects.filter(create_time__gte=date).values('username').distinct().count()
        if counts:
            # 新访问用户  第一次访问的新用户
            new_user = UserCount.objects.filter(create_time__gte=date).values('username').distinct()
            for i in new_user:
                # 查询用户表 获取性别相关信息以及省份信息
                users_man = User.objects.filter(username=i['username'], gender=1).values('username',
                                                                                         'province').distinct()
                if users_man:
                    if users_man[0]['province'] in address_change:
                        if i['username'] in old_user_list:
                            if address_change[users_man[0]['province']] in province_dict_old_man:
                                province_dict_old_man[address_change[users_man[0]['province']]] += 1
                            else:
                                province_dict_old_man[address_change[users_man[0]['province']]] = 1
                            old_man += 1
                        else:
                            if address_change[users_man[0]['province']] in province_dict_new_man:
                                province_dict_new_man[address_change[users_man[0]['province']]] += 1
                            else:
                                province_dict_new_man[address_change[users_man[0]['province']]] = 1
                            new_man += 1
                    man += 1

                users_woman = User.objects.filter(username=i['username'], gender=2).values('username',
                                                                                           'province').distinct()
                print('i am woman users', users_woman)
                if users_woman:
                    if users_woman[0]['province'] in address_change:
                        if i['username'] in old_user_list:
                            if address_change[users_woman[0]['province']] in province_dict_old_woman:
                                province_dict_old_woman[address_change[users_woman[0]['province']]] += 1
                            else:
                                province_dict_old_woman[address_change[users_woman[0]['province']]] = 1
                            old_woman += 1
                        else:
                            if address_change[users_woman[0]['province']] in province_dict_new_woman:
                                province_dict_new_woman[address_change[users_woman[0]['province']]] += 1
                            else:
                                province_dict_new_woman[address_change[users_woman[0]['province']]] = 1
                            new_woman += 1
                    woman += 1
        else:
            man = 0
            woman = 0
            counts = 0
        # 添加所有的用户统计数据
        user_list['man'] = man
        user_list['woman'] = woman
        user_list['all_user'] = counts

        # 所有省份数据累加放进字典
        user_old_list = {}
        user_new_list = {}
        user_old_list['old_man'] = old_man
        user_old_list['old_woman'] = old_woman
        user_old_list['all_user'] = old_man + old_woman
        user_new_list['new_man'] = new_man
        user_new_list['new_woman'] = new_woman
        user_new_list['all_user'] = new_man + new_woman

        # 返回数据
        result_list['all_list'] = user_list
        result_list['old_list'] = user_old_list
        result_list['new_list'] = user_new_list
        result_list['province_dict_old_man'] = sorted(province_dict_old_man.items(), key=lambda x: x[1], reverse=True)
        result_list['province_dict_new_man'] = sorted(province_dict_new_man.items(), key=lambda x: x[1], reverse=True)
        result_list['province_dict_old_woman'] = sorted(province_dict_old_woman.items(), key=lambda x: x[1],
                                                        reverse=True)
        result_list['province_dict_new_woman'] = sorted(province_dict_new_woman.items(), key=lambda x: x[1],
                                                        reverse=True)

        result_code = 1
        return Response({'all_result': result_list, 'result_code': result_code})
